package com.share.device.controller;

import com.share.common.core.web.controller.BaseController;
import com.share.common.core.web.domain.AjaxResult;
import com.share.device.service.IRegionService;
import com.share.system.api.domain.Region;
import com.share.system.api.service.RegionRedisService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Set;

@Tag(name = "地区信息接口管理")
@RestController
@RequestMapping("/region")
public class RegionController extends BaseController
{
    @Autowired
    private IRegionService regionService;

    @Autowired
    private RegionRedisService regionRedisService;

    private static final String ONE_LELEVEL_REGION = "1";

    @Operation(summary = "根据上级code获取下级数据列表")
    @GetMapping(value = "/treeSelect/{parentCode}")
    public AjaxResult treeSelect(@PathVariable String parentCode) {
        return success(regionService.treeSelect(parentCode));
    }


    @Operation(summary = "通过最高等级1获取所有区域信息")
    @GetMapping(value = "/getAllHignLevelRegion")
    public AjaxResult getAllHignLevelRegion() {
        ArrayList<Region> regions = new ArrayList<>();
        Set<String> codesByLevel = regionRedisService.getCodesByLevel(ONE_LELEVEL_REGION);
        for (String code : codesByLevel) {
            Region regionByCode = regionRedisService.getRegionByCode(code);
            regions.add(regionByCode);
        }
        return success(regions);
    }

    /**
     * 通过code获取当前区域信息
     * @param code 区域code
     * @return
     */
    @Operation(summary = "通过code获取区域名称")
    @GetMapping(value = "/getNameByCode/{code}")
    public AjaxResult getNameByCode(@PathVariable String code) {
        return success(regionRedisService.getRegionByCode(code));
    }

    @Operation(summary = "通过code获取当前下一级区域信息")
    @GetMapping(value = "/getNextLevelRegion/{code}")
    public AjaxResult getNextLevelRegion(@PathVariable String code) {
        Set<String> childrenCodes = regionRedisService.getChildrenCodes(code);
        ArrayList<Region> regions = new ArrayList<>();
        for (String childrenCode : childrenCodes) {
            Region regionByCode = regionRedisService.getRegionByCode(childrenCode);
            regions.add(regionByCode);
        }
        return success(regions);
    }


}
